package com.rtf.framework.web.mvc.config.secure.configurer.support;

import com.rtf.framework.common.json.JsonMapper;
import com.rtf.framework.web.http.ResponseParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class AppAuthenticationExceptionEntryPoint implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authenticationException ) throws IOException, ServletException {

		int statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR ;

		String message = authenticationException!=null && authenticationException.getMessage()!=null ?
				authenticationException.getMessage() : "服务器处理错误" ;

		if( authenticationException instanceof InsufficientAuthenticationException ){
			statusCode = HttpServletResponse.SC_FORBIDDEN ;
			message = "请求未认证 或 登录超时" ;
		}

		log.debug( "{}" , message ) ;

		ResponseParam responseParam = ResponseParam.fail() ;
		responseParam.message( message ) ;

		// 设置response
		response.setStatus( statusCode ) ;
		response.setCharacterEncoding("utf-8") ;
		// 回写数据
		PrintWriter printWriter = response.getWriter() ;
		printWriter.write( JsonMapper.toJSONString( responseParam ) ) ;
		printWriter.flush();
		printWriter.close();
	}
}